var dbUtil = nodeRequire("./node_modules/dbUtil");

var tabs = $("#tabs").tabs();
tabCounter = 1;

/**
 * 所有自选股数组<br>
 * 元素格式为：{"sc":"600000","sn":"浦发银行","at":"2017-03-23 14:35:47"}<br>
 * 股票编码，股票名称，加入自选时间
 */
var stockData;

/**
 * 所有打开了tab页的股票数组<br>
 * 元素为：{"sn":"浦发银行", "sc":"600000"}
 */
var oct = new Array();

$(function () {

  getStockList();

  stockData = dbUtil.loadFav();
  listMyFav();

  TimerMeter();

});

function listMyFav() {
  $(".favlt").empty();
  if (null == stockData || "" == stockData) {
    $(".favlt").html("<h3>还没有自选股</h3>");
    return;
  }
  console.info("length of myFavList is {0}".format(stockData.length));
  stockData.forEach(function (data) {
    console.info("this is {0}||{1}".format(data.sn, data.sc));
    var eleDiv = ""
      + "<button class=\"stockQuote\" onclick=\"openNewTab('{0}', '{1}')\">".format(data.sn, data.sc)
      + "    <ul>"
      // + "        <li><span class=\"sName\">" + data[i].sn + "</span><span class=\"sCode\">" + data[i].sc + "</span></li>"
      + "        <li><span class=\"sName\">{0}</span><span class=\"sCode\">{1}</span></li>".format(data.sn, data.sc)
      // + "        <li><span class=\"sName rise\">" + data[i].sn + "</span><span class=\"sCode rise\">" + data[i].sc + "</span></li>"
      // + "        <li><span class=\"rise\">15.90</span><span class=\"lSpan rise\">&uarr;0.02</span><span class=\"lSpan rise\">0.02%</span></li>"
      + "    </ul>"
      + "</button>";
    $(".favlt").append(eleDiv);
  });
}

$("#search_input").autocomplete({
  source: function (req, response) {
    console.info(req.term);
    $.ajax({
      url: "http://news.10jqka.com.cn/public/index_keyboard_{0}_0_5_jsonp.html".format(req.term),
      type: "get",
      dataType: "jsonp",
      jsonp: 'callback',
      jsonpCallback: "jsonp",
      success: function (data) {
        response($.map(data, function (item) {
          // console.info(data);
          // console.info(item);
          if (item.indexOf("股票") > 0) {
            return {
              label: "",
              value: item.split("||")[1]
            }
          }
        }));
      }
    });
  },
  position: { my: "center top-122", at: "center top", of: "#stocksearch" },
  autoFocus: true,
  select: function (e, u) {
    console.info(e + "|" + u.item.value);
    var v = u.item.value;
    var c = v.split(" ")[0];
    var n = v.split(" ")[1];
    console.info(c + "|" + n);
    openNewTab(n, c);
    // openNewTab2(n, c);
  }
});

function openNewTab2(n, c) {
  var tabLi = "<li><a href=\"#tab-{0}\">{1}</a><span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>".format(c, n);
  var newTab = ""
    + "<div id=\"tab-{0}\">".format(n)
    + "<h1>哦也也～～</h1>"
    + "</div>";
  $("#tabUl").append(tabLi);
  $(".menutab").append(newTab);
  tabs.tabs("refresh");
  tabCounter++;

  tabs.on("click", "span.ui-icon-close", function () {
    var panelId = $(this).closest("li").remove().attr("aria-controls");
    $("#" + panelId).remove();
    tabs.tabs("refresh");
  });
}

function openNewTab(n, c) {

  for (var i = 0; i < oct.length; i++) {
    if (oct[i].sc == c) {
      //$(".menutab").find("a").eq(2).click();
      $("#t-" + c).click();
      return;
    }
  }

  var j = {}; j.sn = n, j.sc = c;
  oct.push(j);

  var tabLi = "<li><a href=\"#tab-{0}\" id=\"t-{1}\">{2}</a><span class='ui-icon ui-icon-close' role='presentation' style=\"cursor:pointer;\">{3}</span></li>".format(c, c, n, c);
  var newTab = ""
    + "<div id=\'tab-{0}\'>".format(c)
    + "    <div class=\'stkinfo\'>"
    // + "        <div style=\'width:260px;\'>"
    // + "            <div style=\'width:258px; height:50px; border:1px #a1a1a1 solid; line-height:50px; text-align:center;\'>"
    // + "                <span id=\'stockName\' style=\'font-size:22px; font-weight:bold;\'>" + n + "</span>&nbsp;&nbsp;&nbsp;"
    // + "                <span id=\'stockCode\' style=\'color:#8b4513; font-size:18px; font-weight:bold;\'>" + c + "</span>&nbsp;&nbsp;&nbsp;"
    // + "                <span id=\"favBtn-{0}\">{1}</span>".format(c, opStr)
    // + "            </div>"
    // + "        </div>"
    // + "        <div class=\"cuda\" id=\"cuda-{0}\">".format(c)
    // + "            <table>"
    // + "                <tr>"
    // + "                    <td>今开</td><td>{0}</td>".format(dh["7"])
    // + "                    <td>昨收</td><td>{0}</td>".format(dh["6"])
    // + "                </tr>"
    // + "                <tr>"
    // + "                    <td>最高</td><td>{0}</td>".format(dh["8"])
    // + "                    <td>最低</td><td>{0}</td>".format(dh["9"])
    // + "                </tr>"
    // + "                <tr>"
    // + "                    <td>成交额</td><td>{0}亿</td>".format((parseInt(dh["19"]) / (10e7)).toFixed(2))
    // + "                    <td>成交量</td><td>{0}万</td>".format((parseInt(dh["13"]) / (10e3)).toFixed(1))
    // + "                </tr>"
    // + "                <tr>"
    // + "                    <td>换手</td><td>{0}%</td>".format(parseFloat(dh["1968584"]).toFixed(2))
    // + "                    <td>振幅</td><td>{0}%</td>".format(dh["526792"])
    // + "                </tr>"
    // + "            </table>"
    // + "        </div>"
    // + "        <div style=\'width:258px;float:left; border:1px #a1a1a1 solid; margin-top:5px;\'>"
    // + "            <div class=\'t_cont\'>"
    // // + "                <ul>"
    // // + "                    <li><a href=\'javascript:void(0);\'>五档盘口</a></li>"
    // // + "                    <li><a href=\ 'javascript:void(0);\'>资金流向</a></li>"
    // // + "                </ul>"
    // + "                <div class=\"t_f\" id=\"t_f-{0}\">".format(c)
    // + "                    <p>"
    // + "                        <span class=\'wb\'>委比:<strong>{0}%</strong></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".format(undefined == dh["461256"] ? 0 : dh["461256"])
    // + "                        <span class=\'wc\'>委差:<strong>{0}</strong></span>".format((parseInt(dh["395720"])/100).toFixed(0))
    // + "                    </p>"
    // + "                    <table>"
    // + "                        <tr class=\'s5\'>"
    // + "                            <td>卖五</td><td>{0}</td><td>{1}</td>".format(df["156"], df["157"])
    // + "                        </tr>"
    // + "                        <tr class=\'s4\'>"
    // + "                            <td>卖四</td><td>{0}</td><td>{1}</td>".format(df["152"], df["153"])
    // + "                        </tr>"
    // + "                        <tr class=\'s3\'>"
    // + "                            <td>卖三</td><td>{0}</td><td>{1}</td>".format(df["34"], df["35"])
    // + "                        </tr>"
    // + "                        <tr class=\'s2\'>"
    // + "                            <td>卖二</td><td>{0}</td><td>{1}</td>".format(df["32"], df["33"])
    // + "                        </tr>"
    // + "                        <tr class=\'s1\'>"
    // + "                            <td>卖一</td><td>{0}</td><td>{1}</td>".format(df["30"], df["31"])
    // + "                        </tr>"
    // + "                        <tr class=\'b1\'>"
    // + "                            <td>买一</td><td>{0}</td><td>{1}</td>".format(df["24"], df["25"])
    // + "                        </tr>"
    // + "                        <tr class=\'b2\'>"
    // + "                            <td>买二</td><td>{0}</td><td>{1}</td>".format(df["26"], df["27"])
    // + "                        </tr>"
    // + "                        <tr class=\'b3\'>"
    // + "                            <td>买三</td><td>{0}</td><td>{1}</td>".format(df["28"], df["29"])
    // + "                        </tr>"
    // + "                        <tr class=\'b4\'>"
    // + "                            <td>买四</td><td>{0}</td><td>{1}</td>".format(df["150"], df["151"])
    // + "                        </tr>"
    // + "                        <tr class=\'b5\'>"
    // + "                            <td>买五</td><td>{0}</td><td>{1}</td>".format(df["154"], df["155"])
    // + "                        </tr>"
    // + "                    </table>"
    // + "                    <p>"
    // + "                        <span class=\'wp\'>外盘:<strong>{0}</strong></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".format((parseInt(dh["14"])/100).toFixed(0))
    // + "                        <span class=\'np\'>内盘:<strong>{0}</strong></span>".format((parseInt(dh["15"])/100).toFixed(0))
    // + "                    </p>"
    // + "                </div>"
    // + "                <div id=\'t_z\'>"
    // + "                </div>"
    // + "            </div>"
    // + "        </div>"
    + "    </div>"
    + "    <div style=\'overflow-y:show; height:100%; margin-left:270px;\'>"
    + "        <div style=\'width:580px;\'>"
    + "            <iframe id=\'ifr_chart\' width=\'620px\' height=\'565px\' frameborder=\'0\' scrolling=\'no\' marginwidth=\'0\' marginheight=\'0\' src=\'http://stockpage.10jqka.com.cn/HQ_v3.html#hs_" + c + "\'></iframe>"
    + "        </div>"
    + "    </div>"
    + "</div>";
  $("#tabUl").append(tabLi);
  $(".menutab").append(newTab);

  fillContent(n, c);

  tabs.tabs("refresh");
  tabCounter++;

  // 绑定点击事件：点击“x”关闭tab页
  tabs.on("click", "span.ui-icon-close", function () {
    var c = $(this).text();
    for (var i = 0; i < oct.length; i++) {
      if (oct[i].sc == c) {
        oct.splice(i, 1);
      }
    }
    var panelId = $(this).closest("li").remove().attr("aria-controls");
    $("#" + panelId).remove();
    tabs.tabs("refresh");
  });

  // 转到新开的股票tab页
  $("#t-" + c).click();

}

function fillContent (n, c) {
  var j = {}; j.sc = c;
  var s = dbUtil.getByCode(j);
  var opStr = (null == s ? "<input type=\'button\' onclick=\"addMyFav('{0}', '{1}')\" value=\'加自选\' style=\'cursor:pointer;\'/>" : "<input type=\'button\' onclick=\"removeMyFav('{0}', '{1}')\" value=\'取消自选\' style=\'cursor:pointer;\'/>").format(n, c);

  // 获取基本信息及五档盘口
  var dh = getData(c, "head");  // 基本信息
  var df = getData(c, "five");  // 五档盘口

  var tabContent = ""
      // + "    <div class=\'stkinfo\'>"
      + "        <div style=\'width:260px;\'>"
      + "            <div style=\'width:258px; height:50px; border:1px #a1a1a1 solid; line-height:50px; text-align:center;\'>"
      + "                <span id=\'stockName\' style=\'font-size:22px; font-weight:bold;\'>" + n + "</span>&nbsp;&nbsp;&nbsp;"
      + "                <span id=\'stockCode\' style=\'color:#8b4513; font-size:18px; font-weight:bold;\'>" + c + "</span>&nbsp;&nbsp;&nbsp;"
      + "                <span id=\"favBtn-{0}\">{1}</span>".format(c, opStr)
      + "            </div>"
      + "        </div>"
      + "        <div class=\"cuda\" id=\"cuda-{0}\">".format(c)
      + "            <table>"
      + "                <tr>"
      + "                    <td>今开</td><td>{0}</td>".format(dh["7"])
      + "                    <td>昨收</td><td>{0}</td>".format(dh["6"])
      + "                </tr>"
      + "                <tr>"
      + "                    <td>最高</td><td>{0}</td>".format(dh["8"])
      + "                    <td>最低</td><td>{0}</td>".format(dh["9"])
      + "                </tr>"
      + "                <tr>"
      + "                    <td>成交额</td><td>{0}亿</td>".format((parseInt(dh["19"]) / (10e7)).toFixed(2))
      + "                    <td>成交量</td><td>{0}万</td>".format((parseInt(dh["13"]) / (10e3)).toFixed(1))
      + "                </tr>"
      + "                <tr>"
      + "                    <td>换手</td><td>{0}%</td>".format(parseFloat(dh["1968584"]).toFixed(2))
      + "                    <td>振幅</td><td>{0}%</td>".format(dh["526792"])
      + "                </tr>"
      + "            </table>"
      + "        </div>"
      + "        <div style=\'width:258px;float:left; border:1px #a1a1a1 solid; margin-top:5px;\'>"
      + "            <div class=\'t_cont\'>"
      // + "                <ul>"
      // + "                    <li><a href=\'javascript:void(0);\'>五档盘口</a></li>"
      // + "                    <li><a href=\ 'javascript:void(0);\'>资金流向</a></li>"
      // + "                </ul>"
      + "                <div class=\"t_f\" id=\"t_f-{0}\">".format(c)
      + "                    <p>"
      + "                        <span class=\'wb\'>委比:<strong>{0}%</strong></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".format(undefined == dh["461256"] ? 0 : dh["461256"])
      + "                        <span class=\'wc\'>委差:<strong>{0}</strong></span>".format((parseInt(dh["395720"])/100).toFixed(0))
      + "                    </p>"
      + "                    <table>"
      + "                        <tr class=\'s5\'>"
      + "                            <td>卖五</td><td>{0}</td><td>{1}</td>".format(df["156"], df["157"])
      + "                        </tr>"
      + "                        <tr class=\'s4\'>"
      + "                            <td>卖四</td><td>{0}</td><td>{1}</td>".format(df["152"], df["153"])
      + "                        </tr>"
      + "                        <tr class=\'s3\'>"
      + "                            <td>卖三</td><td>{0}</td><td>{1}</td>".format(df["34"], df["35"])
      + "                        </tr>"
      + "                        <tr class=\'s2\'>"
      + "                            <td>卖二</td><td>{0}</td><td>{1}</td>".format(df["32"], df["33"])
      + "                        </tr>"
      + "                        <tr class=\'s1\'>"
      + "                            <td>卖一</td><td>{0}</td><td>{1}</td>".format(df["30"], df["31"])
      + "                        </tr>"
      + "                        <tr class=\'b1\'>"
      + "                            <td>买一</td><td>{0}</td><td>{1}</td>".format(df["24"], df["25"])
      + "                        </tr>"
      + "                        <tr class=\'b2\'>"
      + "                            <td>买二</td><td>{0}</td><td>{1}</td>".format(df["26"], df["27"])
      + "                        </tr>"
      + "                        <tr class=\'b3\'>"
      + "                            <td>买三</td><td>{0}</td><td>{1}</td>".format(df["28"], df["29"])
      + "                        </tr>"
      + "                        <tr class=\'b4\'>"
      + "                            <td>买四</td><td>{0}</td><td>{1}</td>".format(df["150"], df["151"])
      + "                        </tr>"
      + "                        <tr class=\'b5\'>"
      + "                            <td>买五</td><td>{0}</td><td>{1}</td>".format(df["154"], df["155"])
      + "                        </tr>"
      + "                    </table>"
      + "                    <p>"
      + "                        <span class=\'wp\'>外盘:<strong>{0}</strong></span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".format((parseInt(dh["14"])/100).toFixed(0))
      + "                        <span class=\'np\'>内盘:<strong>{0}</strong></span>".format((parseInt(dh["15"])/100).toFixed(0))
      + "                    </p>"
      + "                </div>"
      + "                <div id=\'t_z\'>"
      + "                </div>"
      + "            </div>"
      + "        </div>"
      // + "    </div>"
      ;

      $("#tab-{0} .stkinfo".format(c)).html(tabContent);

}

function getData(c, f) {
  var urlStr, returnData;
  if ("head" == f) {
    urlStr = "http://d.10jqka.com.cn/v2/realhead/hs_{0}/last.js".format(c);
  } else {
    urlStr = "http://d.10jqka.com.cn/v2/fiverange/hs_{0}/last.js".format(c);
  }
  $.ajax({
    async: false,
    url: urlStr,
    type: "get",
    dataType: "text",
    success: function (d) {
      // console.info(d);
      // console.info(d.split("(")[1].split(")")[0]);
      returnData = (JSON.parse(d.split("(")[1].split(")")[0])).items;
      // console.info(it);
    },
    error: function (e) {
      console.error("fuck", e);
    }
  });
  return returnData;
}

/**
 * [addMyFav description]
 * @param {[type]} sc [description]
 * @param {[type]} cl 市场分类
 */
function addMyFav(n, c) {
  // var mf = {
  //     "sc": c,
  //     "sn": n
  //     "at": new Date().format('yyyy-MM-dd HH:mm:ss')
  // };
  var mf = {};
  mf.sc = c;
  mf.sn = n;
  mf.at = new Date().format('yyyy-MM-dd HH:mm:ss');
  console.log(mf);

  dbUtil.saveFav(mf, function (d) {
    $("#favBtn-" + c).html("<input type=\"button\" onclick=\"removeMyFav('{0}', '{1}')\" value=\"取消自选\" style=\"cursor:pointer;\"/>".format(n, c));
    stockData = d;
  });
  listMyFav();
}

/**
 *
 * @param {*} n
 * @param {*} c
 */
function removeMyFav(n, c) {
  var mf = {}; mf.sc = $("#stockCode").text();
  dbUtil.removeFav(mf, function (d) {
    $("#favBtn-" + c).html("<input type=\"button\" onclick=\"addMyFav('{0}', '{1}')\" value=\"加自选\" style=\"cursor:pointer;\"/>".format(n, c));
    stockData = d;
  });
  listMyFav();
}

function getStockList() {
  $.ajax({
    url: "http://q.10jqka.com.cn/index/index/board/all/field/zdf/order/desc/page/1/ajax/1/",
    type: "get",
    dataType: "html",
    success: function (data) {
      var cssUrl = "";
      $(".slist").html(data);
    }
  });
}

function TimerMeter() {
  setInterval(function () {
    oct.forEach(function (j) {
      fillContent(j.sn, j.sc);
    });
  }, 10000);  // 10秒更新一次股票信息
};
